package cn.sky.demo.test.latchutils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CompletableFutureExample {

    public static void main(String[] args) {
        // 1. 准备一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        System.out.println("主流程开始，准备分发异步任务...");
        
        // 2. 创建 CompletableFuture 任务
        CompletableFuture<Void> userFuture = CompletableFuture.runAsync(() -> {
            try {
                System.out.println("开始获取用户信息...");
                Thread.sleep(1000);
                System.out.println("获取用户信息成功！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, executorService);

        CompletableFuture<Void> orderFuture = CompletableFuture.runAsync(() -> {
            try {
                System.out.println("开始获取订单信息...");
                Thread.sleep(1500);
                System.out.println("获取订单信息成功！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, executorService);

        CompletableFuture<Void> productFuture = CompletableFuture.runAsync(() -> {
            try {
                System.out.println("开始获取商品信息...");
                Thread.sleep(500);
                System.out.println("获取商品信息成功！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, executorService);

        System.out.println("所有异步任务已提交，主线程开始等待...");
        
        // 3. 使用 CompletableFuture.allOf 将所有任务组合起来
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(userFuture, orderFuture, productFuture);

        // 4. 等待组合后的 Future 完成
        try {
            allFutures.get(5, TimeUnit.SECONDS);
            System.out.println("所有异步任务执行成功，主流程继续...");
        } catch (Exception e) {
            // 需要处理多种异常，如 InterruptedException, ExecutionException, TimeoutException
            System.err.println("任务执行超时或出错，主流程中断！ " + e.getMessage());
        }

        // 5. 关闭线程池
        executorService.shutdown();
    }
}